<?php

namespace jueqi;

use OSS\Core\OssException;
use OSS\OssClient;

class QcloudOss
{
    /**
     * 简单上传
     * @param $fileInfo // 文件对象
     * @param $fileName // 保存的文件路径以及文件名
     * @param string $msg // 错误信息
     * @return mixed
     */
    public function uploadFile($fileInfo, string $fileName = '', string &$msg = '')
    {
        if (empty($fileInfo)) {
            $msg = "上传文件为空！";
            return false;
        }
        if (empty($fileName)) {
            $msg = "保存路径不能为空！";
            return false;
        }
        $fileUrl = $fileName;
        $config  = get_sys_config("", 'oss');
        if (empty($config)) {
            $msg = "OSS对象存储未配置！";
            return false;
        }
        $accessKeyId     = $config['oss_app_ley_id'] ?? ''; // Access Key ID
        $accessKeySecret = $config['oss_app_key_secret'] ?? ''; // Access Key Secret
        $endpoint        = $config['oss_endpoint'] ?? ''; // // Bucket所在地域
        $bucket          = $config['oss_bucket'] ?? ''; // 填写Bucket名称

        if (empty($accessKeyId) || empty($accessKeySecret) || empty($endpoint) || empty($bucket)) {
            $msg = "OSS对象存储配置错误或为空！";
            return false;
        }

        // 填写Object完整路径，例如exampledir/exampleobject.txt
        $object = $fileUrl;
        try {
            $content   = $fileInfo->openFile('rb'); // 打开文件
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            return $ossClient->putObject($bucket, $object, $content);
        } catch (OssException $e) {
            $msg = $e->getMessage();
            return false;
        }
    }
}